package com.acme.bankapp.services;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * Class to work with files. Provides methods to save and restore serialized
 * objects and get feed info from file
 * 
 * 
 */
public class DataWorker {

	private final File file;

	public DataWorker(String pathname) throws FileNotFoundException {
		this.file = new File(pathname);
		if (!this.file.exists())
			throw new FileNotFoundException(file.getAbsolutePath()
					+ " not exist");
	}

	/**
	 * Save serialized object
	 * 
	 * @param object
	 * @throws IOException
	 */
	public void save(Serializable object) throws IOException {
		try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(
				new BufferedOutputStream(new FileOutputStream(file)))) {

			objectOutputStream.writeObject(object);
		}
	}

	/**
	 * Restore serialized object from file
	 * 
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public Object restore() throws IOException, ClassNotFoundException {
		try (ObjectInputStream objectOutputStream = new ObjectInputStream(
				new BufferedInputStream(new FileInputStream(file)))) {
			return objectOutputStream.readObject();
		}
	}

	/**
	 * Get feed string from file
	 * 
	 * @return
	 */
	public String loadFeed() {
		StringBuilder builder = new StringBuilder();
		try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
			String line;
			while ((line = reader.readLine()) != null) {
				builder.append(line).append("\n");
			}
		} catch (IOException e) {
			assert false : "Error reading from feed!";
		}
		return builder.toString();
	}

}
